//
//  CouponView.m
//  OrderSeat
//
//  Created by 王威 on 13-12-25.
//  Copyright (c) 2013年 wangwei. All rights reserved.
//

#import "CouponView.h"
#import "MyCouponCell.h"
#import "MyCouponViewController.h"
#import "CouponDetailViewController.h"

@implementation CouponView

- (id)initWithFrame:(CGRect)frame andCouponType:(CouponType)couponType
{
    _couponType = couponType;
    self = [super initWithFrame:frame];
    if (self) {
        _dataSource = [[CouponDataSource alloc] initWithView:self];
        [self initViews];
        [self autoPullRefresh];
    }
    return self;
}

- (void)initViews
{
    _couponTable = [[UITableView alloc] initWithFrame:self.bounds];
    _couponTable.backgroundColor = [UIColor clearColor];
    _couponTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    _couponTable.delegate = _dataSource;
    _couponTable.dataSource = _dataSource;
    [self addSubview:_couponTable];
    
    [self createHeaderView];
}

- (void)autoPullRefresh
{
    [_couponTable setContentOffset:CGPointMake(0, -75) animated:YES];
    [self performSelector:@selector(doPullRefresh) withObject:nil];
}

//执行下拉刷新
-(void)doPullRefresh {
    [_refreshHeaderView egoRefreshScrollViewDidScroll:_couponTable];
    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:_couponTable];
}

-(void)createHeaderView {
    if (_refreshHeaderView && [_refreshHeaderView superview]) {
        [_refreshHeaderView removeFromSuperview];
    }
	_refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:
                          CGRectMake(Zero, Zero - ScreenHeight, ScreenWidth, ScreenHeight)];
    _refreshHeaderView.delegate = self;
    
	[_couponTable addSubview:_refreshHeaderView];
    
    [_refreshHeaderView refreshLastUpdatedDate];
}

#pragma mark data reloading methods that must be overide by the subclass
-(void)beginToReloadData:(EGORefreshPos)aRefreshPos
{
	_reloading = YES;
    
    if (aRefreshPos == EGORefreshHeader)
	{
        [self performSelector:@selector(refreshView) withObject:nil afterDelay:2.0];
    }
}

//刷新调用的方法
-(void)refreshView
{
    _dataSource.pageNumber = 1;
    [_dataSource fetchCoupon];
}

-(void)finishedLoadData
{
    [_couponTable reloadData];
    [self finishReloadingData];

    [self addEmptyText];
}

- (void)addEmptyText
{
    if (_dataSource.couponList.count == 0) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 50, self.width, 30)];
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:20];
        label.textColor = [UIColor grayColor];
        label.text = @"没有数据显示";
        label.tag = 1234;
        [self addSubview:label];
    }else {
        UIView *view = [self viewWithTag:1234];
        [view removeFromSuperview];
    }
}

- (void)finishReloadingData
{
	_reloading = NO;
    
	if (_refreshHeaderView) {
        [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:_couponTable];
    }
}

#pragma mark -
#pragma mark EGORefreshTableDelegate Methods
- (void)egoRefreshTableDidTriggerRefresh:(EGORefreshPos)aRefreshPos
{
	[self beginToReloadData:aRefreshPos];
}

- (BOOL)egoRefreshTableDataSourceIsLoading:(UIView*)view
{
	return _reloading; // should return if data source model is reloading
}

// if we don't realize this method, it won't display the refresh timestamp
- (NSDate*)egoRefreshTableDataSourceLastUpdated:(UIView*)view
{
	return [NSDate date]; // should return date data source was last changed
}

#pragma 将分页加载的数据添加到tableview后面
- (void)appendTableWith:(NSMutableArray *)data
{
    for (int i = 0; i < [data count]; i++) {
        [_dataSource.couponList addObject:[data objectAtIndex:i]];
    }
    
    NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithCapacity:10];
    
    for (int ind = 0; ind < [data count]; ind++) {
        NSIndexPath *newPath = [NSIndexPath indexPathForRow:[_dataSource.couponList indexOfObject:[data objectAtIndex:ind]] inSection:0];
        [insertIndexPaths addObject:newPath];
    }
    
    [_couponTable insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];
    
    self.moreLoading = NO;
}


@end

//=============================================================================================
#pragma ===================数据源类实现==========================================================
//=============================================================================================

#define RefreshTag 1001
#define LoadMoreTag 1002
#define RemoveTag 1003

@implementation CouponDataSource

- (id)initWithView:(id)view
{
    self = [super init];
    if (self) {
        self.view = view;
        _couponList = [[NSMutableArray alloc] initWithCapacity:10];
    }
    return self;
}

- (void)fetchCoupon
{
    NSString *url = [NSString stringWithFormat:[self getAPI], [AppSetting userName], _pageNumber];
    [self get:url tag:_pageNumber == 1 ? RefreshTag : LoadMoreTag];
}

- (NSString *)getAPI
{
    return _view.couponType == NewCoupon ? API_COUPONING : API_COUPONED;
}

- (void)removeWithId:(NSString *)couponId
{
    NSString *url = [NSString stringWithFormat:API_DEL_COUPON,couponId];
    [self get:url tag:RemoveTag];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    CLog(@"%@", request.responseString);
    NSDictionary *json = [request.responseData JSONValue];
    
    if ([[json objectForKey:@"error_code"] intValue] == 0) {
        NSDictionary *data = [json objectForKey:@"data"];
        
        if (request.tag == RefreshTag) {
            self.couponList = [data objectForKey:@"youhuiquan"];
            [_view finishedLoadData];
        }
        if (request.tag == LoadMoreTag) {
            [_view appendTableWith:[data objectForKey:@"youhuiquan"]];
        }
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    _pageNumber--;
    [_view finishedLoadData];
    [super requestFailed:request];
}

#pragma mark-=======================requestFinished回调========================================

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.couponList count];
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CouponCell";
    MyCouponCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"MyCouponCell" owner:self options:nil];
        cell = [array objectAtIndex:0];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }
    
    NSDictionary *dic = [self.couponList objectAtIndex:indexPath.row];
    [cell setContent:dic];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = [self.couponList objectAtIndex:indexPath.row];
    NSString *couponId = [dic objectForKey:@"yid"];
    
    CouponDetailViewController *detailVC = [[CouponDetailViewController alloc] initWithCouponId:couponId];
    [_view.couponVC.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
	if (_view.refreshHeaderView)
	{
        [_view.refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	if (_view.refreshHeaderView)
	{
        [_view.refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    }
}

#pragma 分页加载
-(void)tableView:(UITableView *)tableView  willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == _couponList.count-1) {
        if (!self.view.moreLoading) {
            _pageNumber++;
            [self fetchCoupon];
            
            self.view.moreLoading = YES;
        }
    }
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        NSDictionary *dic = [_couponList objectAtIndex:indexPath.row];
        NSString *_id = [dic objectForKey:@"id"];
        
        [self removeWithId:_id];
        [_couponList removeObject:dic];
        
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];        
    }
}

@end
